package com.simon.nio.test2;

import com.simon.nio.CharsetHelper;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by changf on 2017/7/13.
 */
public class NioServer {


     private ByteBuffer byteBuffer;


    private Selector selector;


    public static void main(String[] args) throws Exception{
        NioServer server=new NioServer();
        server.init();
        System.out.println("start server 8383");

        server.listen();

    }

    private void init()throws Exception{
        ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();

        serverSocketChannel.socket().bind(new InetSocketAddress(8989));
        serverSocketChannel.configureBlocking(false);
        selector= Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        byteBuffer=ByteBuffer.allocate(1024);
    }



    private void listen()throws Exception{
        System.out.println("server start listen");
        while(true){
        selector.select();
        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        Iterator<SelectionKey> iterator = selectionKeys.iterator();
        while(iterator.hasNext()){
            System.out.println("server listen ing,,,,,,,,,,,,,");
            SelectionKey key = iterator.next();
            iterator.remove();
            SocketChannel channel;
            if(key.isAcceptable()){
                System.out.println("server acceptable...");
                ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                channel=serverSocketChannel.accept();
                channel.configureBlocking(false);
                channel.register(selector,SelectionKey.OP_READ);

            }else if(key.isReadable()){
                System.out.println("server readable...");

                channel= (SocketChannel) key.channel();
                byteBuffer.clear();
                int read = channel.read(byteBuffer);
                if(read>0) {
                    byteBuffer.flip();
                    CharBuffer charBuffer = CharsetHelper.decode(byteBuffer);
                    String question = charBuffer.toString();
                    System.out.println("server question[]【】:"+question);
                    if(question.equals("hello")){
                        channel.write(CharsetHelper.encode(CharBuffer.wrap("hello world nio")));
                    }else{
                        channel.write(CharsetHelper.encode(CharBuffer.wrap("nio i don't understand")));
                    }


                }else {
                    Thread.sleep(10000);
                    System.out.println("server channel close");
                    channel.close();
                }
            }


        }


    }}
}
